<template>
  <el-dialog
    top="30px"
    width="800px"
    :title="title"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <ul v-loading="loading" class="list-inline">
      <li v-loading="saveLoading" class="attach-item">
        <upload-oss
          multiple
          accept="image/*"
          listType="picture-card"
          ref="upload_oss"
          :file-list="fileList"
          :on-change="handleUploadChange"
          :on-complete="handleImagesComplete"
        ></upload-oss>
      </li>

      <li v-for="(item, index) in dataList" class="attach-item" :key="index">
        <div class="attach-item-wrap" :class="{ 'is-odd': item.odd }">
          <img
            alt=""
            class="attach-item-img"
            :src="item.image"
            @click.stop="handlePreview(index)"
          />
          <div
            class="attach-item-label badge badge-bill cursor-pointer"
            :class="`badge-${item.labelType}`"
            @click="handleChangeLabel(item.id)"
          >
            {{ item.labelKey }}
          </div>
          <div class="attach-item-delete">
            <button
              class="btn btn-sm btn-light"
              type="button"
              @click="deleteData(item.id, item.image)"
            >
              <i class="el-icon-delete"></i>
            </button>
          </div>
        </div>
      </li>
    </ul>

    <el-dialog
      append-to-body
      center
      title="选择图片标签"
      width="360px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      :visible.sync="labelDialogVisible"
    >
      <div>
        <el-tag
          v-for="(item, index) in dynamicTags"
          style="margin-left: 10px; margin-top: 5px"
          :disable-transitions="false"
          :key="index"
        >
          <el-button size="mini" type="text" @click="handleSelectLabel(item)">{{ item }}</el-button>
        </el-tag>

        <el-input
          v-if="inputVisible"
          v-model="inputValue"
          class="input-new-tag"
          ref="saveTagInput"
          size="small"
          style="margin-left: 10px; margin-top: 5px; width: 120px"
          @blur="handleInputConfirm"
          @keyup.enter.native="handleInputConfirm"
        ></el-input>

        <el-button
          v-else
          class="button-new-tag"
          size="small"
          style="margin-left: 10px; margin-top: 5px; border-radius: 4px; line-height: 20px"
          @click="showInput"
        >
          + 自定义标签
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { arrayFromString } from '@vimi/utils-tool'
import { deleteOss } from '@/common/api/oss'

export default {
  components: {},
  props: {
    title: { type: String, default: '上传附件' },
    visible: Boolean,
    queryId: { type: String, required: true },
  },
  data() {
    return {
      dynamicTags: ['生产条件', '生产设施', '基础设施', '其它'],
      tableName: 'datum_customer_attachment',
      loading: false,
      saveLoading: false,
      customerName: '',
      fileList: [],
      dataList: [],
      selectId: '',
      selectKey: '',
      labelDialogVisible: false,
      inputVisible: false,
      inputValue: '',
    }
  },
  computed: {
    images() {
      return this.dataList.map(img => {
        return { src: img.image, title: '' }
      })
    },
  },
  watch: {
    queryId() {
      this.getData()
    },
  },
  created() {
    this.getTag()
  },
  mounted() {},
  methods: {
    getTag() {
      this.$api
        .getData('credit', 'credit_attachment_tags', { 'is_comm_used.eq': '1' })
        .then(res => {
          this.dynamicTags = ((res && res.data) || [])
            .filter(item => item.tag_name)
            .map(item => item.tag_name)
        })
    },
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose() {
      this.fileList = []
      // this.dataList = []
      this.$emit('update:visible', false)
    },

    async getData() {
      if (!this.queryId) {
        return
      }

      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(
          'credit',
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
          },
          { create_time: 'desc' }
        )
      )
      this.loading = false

      if (err) {
        return this.$message.error('获取附件图片失败，请重试！')
      }

      this.dataList = []
      this.fileList = []
      if (res && res.data) {
        let odd = false
        for (const data of res.data) {
          odd = !odd
          const images = arrayFromString(data.attachment)
          for (const image of images) {
            this.dataList.push({
              id: data.id,
              labelKey: data.attachment_type || '其他',
              labelType: 'success',
              image,
              odd,
            })
          }
        }
      }
    },

    handleUploadChange(file) {
      if (!(!file || file.status === 'success')) {
        this.selectId = ''
        this.labelDialogVisible = true
      }
    },

    handleDialogClose(done) {
      this.fileList = []
      done()
    },

    handleSelectLabel(labelKey) {
      this.labelDialogVisible = false
      this.selectKey = labelKey
      if (this.selectId) {
        this.putData()
      } else {
        this.$refs.upload_oss.submit()
        this.saveLoading = true
      }
    },

    handleChangeLabel(id) {
      this.selectId = id
      this.labelDialogVisible = true
    },

    async handleImagesComplete(images) {
      if (!images.length) {
        return this.$message.warning('没有要上传的图片！')
      }

      const datas = images.map(image => {
        return {
          attachment: image.url ? `["${image.url}"]` : '',
          attachment_type: this.selectKey,
          lender_idcard: this.queryId,
          customer_related_id: this.queryId,
        }
      })

      this.addDatas(datas)
    },

    handlePreview(index) {
      this.$utils.viewer({
        images: this.images,
        index,
      })
    },

    async addDatas(datas) {
      this.saveLoading = true
      const [res] = await this.$utils.promise(this.$api.addBatch('credit', this.tableName, datas))
      this.saveLoading = false
      if (res) {
        this.$message.success('添加附件成功！')
        this.getData()
      } else {
        this.$message.error('添加附件失败，请重试！')
      }
    },

    async putData() {
      this.saveLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData('credit', this.tableName, this.selectId, {
          attachment_type: this.selectKey,
        })
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('修改成功！')
        this.getData()
      } else {
        this.$message.error('修改附件失败，请重试！')
      }
    },

    deleteData(id, url) {
      this.$utils
        .msgbox({
          message: '确定删除该附件？',
          type: 'warning',
          beforeClose: () =>
            Promise.all([this.$api.deleteData('credit', this.tableName, id)], deleteOss(url)),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style scoped lang="scss">
.attach-item {
  display: inline-block;
  vertical-align: top;
  margin-right: 5px;
  margin-bottom: 5px;
}

.attach-item-wrap {
  overflow: hidden;
  position: relative;
  width: 148px;
  height: 148px;
  border-radius: 4px;
  border: 1px solid #c0ccda;
  padding: 2px;

  &.is-odd {
    border-color: green;
  }

  .attach-item-img {
    width: 100%;
    height: 100%;
    border-radius: 2px;
  }

  .attach-item-label {
    position: absolute;
    top: 5px;
    left: 5px;
    padding: 0.5rem 0.85rem;
    box-shadow: 1px 2px 4px rgba(0, 0, 0, 0.4);
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .attach-item-delete {
    position: absolute;
    top: 5px;
    right: 5px;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: -1px 2px 4px rgba(0, 0, 0, 0.4);
  }
}
</style>
